#include "Counter.h"
//�����������  ���������� ���� ���������� � ���
Counter* Counter::Head = nullptr;
size_t Counter::m_curCounters = 0;

Counter::Counter(const char* Str):m_owners(0)
{
	m_pStr = new char[strlen(Str) + 1];
	strcpy_s(m_pStr, strlen(Str) + 1, Str);	
	
	//�������� � ������ (������ ������)
	pNext = Head;// ������ ��� ������ �� �����
	Head = this;
	
	m_curCounters++;
}

Counter* Counter::CreateCounter(const char* Str)
{
	Counter* pCur = Head;
	for (size_t i = 0; i<m_curCounters; i++)//����� �� ������ �� ���������� ������
	{
		//stcmp ������ ��� �� ����� ������ �������� == MyStryng, �.� ��� �� MyStryng
		if (strcmp(pCur->m_pStr,Str) == 0) 	{	return pCur;	}	//������ ���������� � ������
		pCur = pCur->pNext;
	}		
	return new Counter(Str);	//��� ������
}

void Counter::AddOwner()
{
	m_owners++;
}

void Counter::RemoveOwner()
{
	m_owners--;
	
	if (m_owners == 0)
	{
		delete this;
	}
}

Counter::~Counter()
{
	delete[] m_pStr;
	m_pStr = nullptr;	

	//��������� �� ������
	
	//�������� �� ������
	if (this == Head)
	{ Head = Head->pNext;}
	else
	{ //pPrev ��������� ��� ��������� ����������
		Counter* pPrev = Head;
		Counter* pCur = Head->pNext;

		for (size_t i = 1; i < m_curCounters; i++)//����� �� ������ �� ���������� ���������
		{
			if (this == pCur) { pPrev->pNext = this->pNext; break; }//��������� ����������� ���������� ��������� ��������
			pPrev = pCur;
			pCur = pCur->pNext;
		}
	}
	m_curCounters--;
}

void Counter::Swap(Counter* Other)
{
	Counter* pPrev = Head;
	Counter* pCur = Head->pNext;

	Counter* Other_pPrev = Head;
	Counter* Other_pCur = Head->pNext;

	//���� ����������
	for (size_t i = 1; i < m_curCounters; i++)//����� �� ������ �� ���������� ���������
	{
		if(this==Head) { break; }
		if (this == pCur) {break;}
		pPrev = pCur;
		pCur = pCur->pNext;
	}
	
	for (size_t i = 1; i < m_curCounters; i++)//����� �� ������ �� ���������� ���������
	{
		if (Other == Head) { break; }
		if (Other == Other_pCur) { break; }
		Other_pPrev = Other_pCur;
		Other_pCur = Other_pCur->pNext;
	}

	if (this->pNext == Other )
	{
		if (this != Head) { pPrev->pNext = Other; }
		this->pNext = Other->pNext;
		Other->pNext = this;
		if (this == Head) { Head = Other;}
		return;
	}
	if (Other->pNext == this)
	{
		if (Other != Head) { Other_pPrev->pNext = this; }
		Other->pNext = this->pNext;
		this->pNext = Other;
		if (Other == Head) { Head = this;}
		return;
	}

	if (this != Head) { pPrev->pNext = Other; }
	if (Other != Head) { Other_pPrev->pNext = this; }
	Counter* tmp = this->pNext;
	this->pNext = Other->pNext;
	Other->pNext = tmp;

	if (this == Head) {	Head = Other; return;}
	if (Other == Head) { Head = this; return; }

	//pPrev->pNext = this->pNext;
}
